import Vue from 'vue'
import VueRouter from 'vue-router'
// import Login from '@/views/login'
const Login = () => import('../views/login/index.vue')
const Layout = () => import('@/views/layout')
// import Layout from '@/views/layout'
const Articles = () => import('@/views/articles')
const Images = () => import('@/views/images')
// import Articles from '@/views/articles'
// import EditArticle from '@/views/articles/add.vue'
// import Images from '@/views/images'
Vue.use(VueRouter)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '*',
    name: 'page404',
    component: () => import('../views/page404')
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    children: [
      {
        path: '/',
        name: 'welcome',
        component: () => import('../views/welcome')
      },
      {
        path: 'articles',
        name: 'articles',
        component: Articles
      },
      // {
      //   path: 'editArticle',
      //   name: 'editArticle',
      //   component: EditArticle // 当前是path传参 如果是name传参需要path: 'editArticle/:id'
      // },
      {
        path: 'images',
        name: 'Images',
        component: Images
      },
      {
        path: 'fans',
        name: 'fans',
        component: () => import('../views/fans')
      },
      {
        path: 'addArticle',
        name: 'addArticle',
        component: () => import('../views/addArticle')
      },
      {
        path: 'comment',
        name: 'comment',
        component: () => import('../views/comment')
      },
      {
        path: 'settings',
        name: 'settings',
        component: () => import('../views/settings')
      }
    ]
  }
]

const router = new VueRouter({
  routes
})
// 路由导航守卫
// 所有的路由页面中跳转，都会先进入到这个函数中来。
// to: 要跳入的路由信息。你要去哪里
// from: 要跳出的路由信息。你从哪里来
// next: 放行方法
//   - next() : 正确跳转。允许进入到 to 路由
//   - next(路由地址) : 不允许去to，而转去指定的路由地址
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    const token = localStorage.getItem('tokenInfo')
    if (token) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
  if (to.path === '/login') {
    const token = localStorage.getItem('tokenInfo')
    if (token) {
      next('/')
    } else {
      next()
    }
  }
})
export default router
